package com.hzm.test.service;

import com.hzm.test.model.Club;
import com.hzm.test.config.CacheManagerNames;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;

@Component
public class ClubService {
    /**
     * @param clubCode
     * @return
     */
    @Cacheable(value = "club", key = "#clubCode", unless = "#result==null || #result.size() == 0"
            // 也可以不写manager，默认就是 REDIS_CACHE_MANAGER
            // ,cacheManager = CacheManagerNames.REDIS_CACHE_MANAGER
    )
    public List<Club> listRankByCache(String clubCode) {
        System.out.println("listRankByCache: ");
        return listRank(clubCode);
    }

    @CachePut(value = "club", key = "#clubCode", unless = "#result==null || #result.size() == 0",
            cacheManager = CacheManagerNames.REDIS_CACHE_MANAGER)
    public List<Club> listRankCacheUpdate(String clubCode) {
        System.out.println("listRankCacheUpdate: ");
        return listRank(clubCode);
    }

    private List<Club> listRank(String clubCode) {
        List<Club> list = new LinkedList<>();

        int length = new Random().nextInt(3);

        System.out.println("-----length: " + length);

        for (int i = 1; i <= length; i++) {
            list.add(new Club(new Random().nextInt(i*100) + "_uid", clubCode));
        }

        return list;
    }
}
